package com.google.gwt.mobile.phonegap;

import java.util.logging.Level;
import java.util.logging.Logger;

import com.google.gwt.core.client.GWT;
import com.google.gwt.mobile.phonegap.api.Event;
import com.google.gwt.mobile.phonegap.factory.PhoneGapNative;
import com.google.gwt.mobile.phonegap.resources.JavaScriptInjector;
import com.google.gwt.resources.client.TextResource;
import com.google.gwt.user.client.Window;

/**
 * The Class PhoneGap.
 */
public final class PhoneGap {
  private static final Logger logger = Logger.getLogger("PhoneGap");

  /** The Constant RUNTIME. */
  public static final PhoneGapNative RUNTIME = GWT.create(PhoneGapNative.class);

  private static boolean isDebugMode = false;

  /**
   * Checks if is debug mode.
   * 
   * @return true, if is debug mode
   */
  public static boolean isDebugMode() {
    return isDebugMode;
  }

  /**
   * Sets the debug mode.
   * 
   * @param debugMode the new debug mode
   */
  public static void setDebugMode(final boolean debugMode) {
    PhoneGap.isDebugMode = debugMode;
  }

  private static boolean loadApi() {
    if (isDebugMode) {
      logger.log(Level.INFO, RUNTIME.toDebugString());
    }

    if (RUNTIME.getDeviceType() == DeviceType.UNSUPPORTED) {
      return false;
    }

    TextResource res = RUNTIME.getResource();
    if (res == null) {
      return false;
    }
    JavaScriptInjector.injectInHead(RUNTIME.getResource().getText());

    return true;
  }

  /**
   * Initializes the native API.
   * 
   * @param handler the handler
   */
  public static void init(final DeviceReadyHandler handler) {
    logger.log(Level.INFO, "User agent: " + Window.Navigator.getUserAgent());

    if (loadApi()) {
      logger.log(Level.INFO, "Native API loaded.");

      Event.onDeviceReady(new Event.Callback() {
        @Override
        public void onEventFired() {
          logger.log(Level.INFO, "Dispatching device ready event.");

          handler.onDeviceReady();
        }
      });

      bindNativePhonegapToDevice();
    } else {
      logger.log(Level.INFO, "Native API unavailable.");
    }
  }

  /**
   * Bind native phonegap to device.
   */
  public native static void bindNativePhonegapToDevice() /*-{
		if ($wnd.PhoneGap == null) {
			return;
		}

		$wnd.PhoneGap.onDOMContentLoaded.fire();
		$wnd.PhoneGap.onNativeReady.fire();
  }-*/;
}
